<script setup lang='ts' name="rights-management-add">
import { getModalList, memberIsRegister, memberLevelHttp } from '@fl/api/anjutong'
import UpLoadBtn from '@fl/components/upLoad-oss.vue'
import { ElButton, ElCard, ElCheckbox, ElCol, ElForm, ElFormItem, ElInput, ElRow, ElTable, ElTableColumn } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { nextTick, toRefs } from 'vue'

import CheckItem from './check-item.vue'
import { useForm } from './hooks/use-form'
import { useRule } from './hooks/use-rule'

const props = withDefaults(defineProps<{
    data?: any
    isAdd: boolean
}>(), {
    data: () => { },
})

const emits = defineEmits(['update:modelValue', 'confirm'])
const { data, isAdd } = toRefs(props)

const { state } = useForm()
const { rules } = useRule()
const form = ref<any>({ ...state })

const show = ref(false)
const selected = ref<any>([])
const tableRef = ref()

const formRef = ref()
const rightsRef = ref()
const tableData = ref<any>([])
const rights = ref<any>([])

// 是否注册 已经注册过 禁用注册会员
const isRegister = ref(false)

async function doSave() {
    await formRef.value.validate((valid, fields) => {
        if (valid) {
            const rights = rightsRef.value.getData()
            const params: any = {
                ...form.value,
                rights,
            }

            memberLevelHttp(isAdd.value ? 'post' : 'put', params).then((res: any) => {
                console.log(res)
                close()
                emits('confirm')
            })
        }
        else { console.log('error submit!', fields) }
    })
}

function doConfirm() {
    show.value = false

    if (selected.value.length) {
        // 权益规则回显
        selected.value.forEach((item: any) => {
            const target = rights.value.find((v: any) => v.rightId === item.rightId) ?? ''
            if (target && target.rules.length) {
                const ruleId = target.rules.find((v: any) => v.selected === 1)?.ruleId ?? ''
                if (ruleId && item.rules.length) {
                    item.rules.forEach((ite: any) => {
                        if (ite.id === ruleId) {
                            ite.selected = 1
                            ite.ruleId = ruleId
                        }
                    })
                }
            }
        })

        rights.value = cloneDeep(selected.value)
    }
    else { rights.value = [] }
}

function handleSelectionChange(val: any) {
    selected.value = val
}

function close() {
    emits('update:modelValue', true)
}

function doClose() {
    show.value = false
    tableRef.value!.clearSelection()
}
async function openDiaglog() {
    show.value = true
    await nextTick()
    setDefault(rights.value)
}

// 会员权益回显
function setDefault(data: any) {
    const target: any = []
    data.forEach((v: any) => {
        const right = tableData.value.find((item: any) => item.rightId === v.rightId)
        target.push(right)
    })
    selected.value = target

    if (target.length) {
        target.forEach((row: any) => {
            tableRef.value!.toggleRowSelection(row, true)
        })
    }
    else {
        tableRef.value!.clearSelection()
    }
}

function checkChange(val: any, key: string) {
    if (val === '0' || val === 0)
        form.value[key] = ''
}

// 会员权益多选 联动弹框表格多选
function itemChange(item: any, isChecked: boolean) {
    if (isChecked) {
        rights.value.push(item)
    }
    else {
        const arr: any = []
        rights.value.forEach((row: any) => {
            if (row.rightId !== item.rightId)
                arr.push(row)
        })

        rights.value = [
            ...arr,
        ]
    }
}

// 查询会员权益
function getData() {
    getModalList({ page: 1, size: 9999 }).then((res: any) => {
        const target = res?.records ?? []

        // 专属特权无规则
        target.forEach((v: any) => {
            if (v.type === 0)
                v.rules = []
        })

        // 已禁用的权益不展示
        tableData.value = target.filter((v: any) => v.status !== 0)

        init()
    })
}

// 配置操作
async function doConfig() {
    show.value = true
    await getData()
    setTimeout(() => {
        setDefault(rights.value)
    }, 500)
}

async function getRegister() {
    const levelId = form.value.levelNo
    const res = await memberIsRegister({ levelId })
    isRegister.value = res !== '1'
}

async function init() {
    if (isAdd.value) {
        form.value = {
            ...state,
        }
        getRegister()
    }
    else {
        const res = await memberLevelHttp('get', data.value.levelId)
        isRegister.value = res.levelNo !== 1

        // TODO: 专属特权无规则 接口没做 前端处理
        const target: any = res.rights
        target.forEach((v: any) => {
            const item = tableData.value.find((ite: any) => ite.rightId === v.rightId)
            if (item && item.type === 0)
                v.rules = []
        })

        rights.value = target
        form.value = {
            ...state,
            ...res,
        }
    }
}

getData()

defineExpose({
    doConfig,
})
</script>

<template>
    <ElCard>
        <ElForm ref="formRef"
                :inline="true"
                :model="form"
                :rules="rules"
                label-width="auto"
        >
            <ElRow>
                <ElCol :span="6">
                    <ElFormItem label="等级"
                                prop="levelNo"
                    >
                        <ElInput v-model="form.levelNo">
                            <template #prepend>
                                LV
                            </template>
                        </ElInput>
                    </ElFormItem>
                </ElCol>

                <ElCol :span="6">
                    <ElFormItem label="等级名称"
                                prop="levelName"
                    >
                        <ElInput v-model="form.levelName" />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow>
                <ElCol :span="12">
                    <ElFormItem label="等级图片"
                                prop="levelIcon"
                    >
                        <UpLoadBtn v-model="form.levelIcon" />
                    </ElFormItem>

                    <ElFormItem label="背景图片"
                                prop="levelImg"
                    >
                        <UpLoadBtn v-model="form.levelImg" />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow>
                <ElCol :span="12">
                    <ElFormItem label="升级条件"
                                prop="type"
                    >
                        <ElCol :span="24">
                            <ElCheckbox v-model="form.isRegister"
                                        :true-value="1"
                                        :false-value="0"
                                        :disabled="isRegister"
                                        label="注册会员"
                            />

                            <span class="tips">仅LV1级可编辑此信息</span>
                        </ElCol>

                        <ElCol :span="24"
                               flex
                        >
                            <ElCol :span="12">
                                <ElCheckbox v-model="form.isTotalPrice"
                                            :true-value="1"
                                            :false-value="0"
                                            label="累计消费"
                                            @change="checkChange($event, 'totalPrice')"
                                />
                            </ElCol>

                            <ElCol :span="12">
                                <ElInput v-if="form.isTotalPrice"
                                         v-model="form.totalPrice"
                                         style="width: 150px"
                                         placeholder="请输入"
                                         size="small"
                                >
                                    <template #append>
                                        元
                                    </template>
                                </ElInput>
                            </ElCol>
                        </ElCol>

                        <ElCol :span="24"
                               flex
                        >
                            <ElCol :span="12">
                                <ElCheckbox v-model="form.isGrowth"
                                            label="成长值"
                                            :true-value="1"
                                            :false-value="0"
                                            @change="checkChange($event, 'levelGrowth')"
                                />
                            </ElCol>

                            <ElCol :span="12">
                                <ElInput v-if="form.isGrowth"
                                         v-model="form.levelGrowth"
                                         style="width: 150px"
                                         size="small"
                                         placeholder="请输入"
                                />
                            </ElCol>
                        </ElCol>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow>
                <ElFormItem label="会员权益"
                            prop="type"
                            class="member-col"
                >
                    <CheckItem ref="rightsRef"
                               :data="rights"
                               @check-change="itemChange"
                    />

                    <div class="title_color"
                         @click="openDiaglog"
                    >
                        配置会员权益
                    </div>
                </ElFormItem>
            </ElRow>

            <!-- <ElRow>
                <ElCol :span="12">
                    <ElFormItem label="升级礼包"
                                prop="type"
                    >
                        <ElCol :span="24"
                               flex
                        >
                            <ElCol :span="12">
                                <ElCheckbox v-model="form.isGiftCoupon"
                                            true-value="1"
                                            false-value="0"
                                            label="送优惠券"
                                />
                            </ElCol>

                            <ElCol :span="12">
                                <div class="title_color">
                                    选择优惠券
                                </div>
                            </ElCol>
                        </ElCol>

                        <ElCol :span="24"
                               flex
                        >
                            <ElCol :span="12">
                                <ElCheckbox v-model="form.isGiftPoints"
                                            true-value="1"
                                            false-value="0"
                                            label="送积分"
                                />
                            </ElCol>

                            <ElCol :span="12">
                                <ElInput v-if="form.isGiftPoints"
                                         v-model="form.levelPoints"
                                         style="width: 150px"
                                         placeholder="请输入"
                                         size="small"
                                >
                                    <template #append>
                                        分
                                    </template>
                                </ElInput>
                            </ElCol>
                        </ElCol>
                    </ElFormItem>
                </ElCol>
            </ElRow> -->

            <ElRow>
                <ElFormItem label="等级状态"
                            prop="status"
                >
                    <el-switch v-model="form.status"
                               :active-value="1"
                               :inactive-value="0"
                    />
                </ElFormItem>
            </ElRow>

            <ElRow>
                <ElButton type="primary"
                          @click="doSave"
                >
                    提交
                </ElButton>

                <ElButton @click="close">
                    返回
                </ElButton>
            </ElRow>
        </ElForm>
    </ElCard>

    <ElDialog v-model="show"
              title="配置权益"
              width="800"
    >
        <ElTable ref="tableRef"
                 :data="tableData"
                 :height="400"
                 style="width: 100%"
                 @selection-change="handleSelectionChange"
        >
            <ElTableColumn type="selection"
                           width="55"
            />

            <ElTableColumn label="权益名称"
                           property="rightName"
            />

            <ElTableColumn property="typeName"
                           label="权益类型"
            >
                <template #default="scope">
                    <span class="title_color">{{ scope.row.typeName }}</span>
                </template>
            </ElTableColumn>

            <ElTableColumn property="info"
                           label="权益说明"
                           show-overflow-tooltip
            />

            <ElTableColumn property="status"
                           label="权益状态"
                           show-overflow-tooltip
            >
                <template #default="scope">
                    {{ scope.row.status ? '启用' : '停用' }}
                </template>
            </ElTableColumn>
        </ElTable>

        <template #footer>
            <div class="dialog-footer">
                <ElButton @click="doClose">
                    取消
                </ElButton>

                <ElButton type="primary"
                          @click="doConfirm"
                >
                    确认
                </ElButton>
            </div>
        </template>
    </ElDialog>
</template>

<style lang="less" scoped>
.tips {
    color: var(--el-disabled-text-color);
    margin-left: 20px;
    font-size: 13px;
    position: relative;
    top: -2px;
}

.title_color {
    color: var(--el-color-primary-dark-2);
    cursor: pointer;
    transform: translateX(-133px);
}

.flex_column {
    display: flex;
    flex-direction: column;
}

.member-col {
    :deep(.el-form-item__content) {
        display: flex;
        flex-direction: column;
    }
}
</style>
